package com.peanut.baby.mvp.record;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;

import androidx.annotation.NonNull;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.Record;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.uploader.UploadMgr;
import com.peanut.devlibrary.compressor.Compressor;
import com.tencent.mars.xlog.Log;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/7/20.
 */

public class RecordEditPresenter implements RecordEditContract.Presenter {
    private static final String TAG = RecordEditPresenter.class.getSimpleName();
    RecordEditContract.View view;

    private List<UploadConf> configs;
    Activity activity;
    public RecordEditPresenter(RecordEditContract.View view,Activity activity) {
        this.view = view;
        this.activity = activity;
    }

    @Override
    public void checkPermissionBeforeSelectPhoto(final Activity activity) {
        AndPermission.with(activity)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .rationale(new RationaleListener() {

                    @Override
                    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                        AlertDialog.newBuilder(activity)
                                .setTitle("提醒")
                                .setMessage("你已拒绝过相机或写文件权限，再次拒绝将无法上传照片哦！")
                                .setPositiveButton("授予", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.resume();
                                    }
                                })
                                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                    }
                                })
                                .show();
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        Log.d("LauncherActivity", "PermissionListener.SUCCESS");
                        view.onPermissionGranted(grantPermissions);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        Log.d("LauncherActivity", "PermissionListener.FAIL");
                        view.onPermissionDenied(deniedPermissions);
                    }
                })
                .start();
    }

    @Override
    public void submitRecord(int flag,String type, String content, String images) {
        Observable obs = (flag == RecordEditActivity.TYPE_ZHENLIAO ? RetrofitClient.getInstance().submitZhenliao(InitManager.getInstance().getUserId(),
                type,
                content,
                images,
                InitManager.getInstance().getUser().userToken) : RetrofitClient.getInstance().submitTiaoli(InitManager.getInstance().getUserId(),
                type,
                content,
                images,
                InitManager.getInstance().getUser().userToken));
        obs.compose(BaseScheduler.<Record>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<Record>() {
            @Override
            protected void onHandleSuccess(Record o) {
                view.onSubmitRecordSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onRequestFailed(msg);
            }

        });

    }

    @Override
        public void compressAndUploadPicture(final List<String> photos) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                configs = new ArrayList<>();
                doCompressAndUploadPhoto(photos, 0);

            }
        }).start();
    }


    public void reUpload(final List<UploadConf> failedConfigs) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                configs = new ArrayList<>();
                reUpload(failedConfigs, 0);
//                view.onPictureUploadFinished(configs);
            }
        }).start();
    }

    private void reUpload(final List<UploadConf> photos, final int index) {
        if (index >= photos.size()) {
            view.onPictureUploadFinished(configs);
            return;
        }
        Log.d(TAG, "doCompressAndUploadPhoto " + index);
        UploadMgr.getInstance().reUploadImage(photos.get(index), new UploadMgr.UploadListener() {
                    @Override
                    public void onQueryToken() {
                    }

                    @Override
                    public void onStartUpload() {

                    }

                    @Override
                    public void onUploadProgress(int total) {

                    }

                    @Override
                    public void onUploadSuccess(UploadConf config) {
                        configs.add(config);
                        reUpload(photos, index + 1);
                    }

                    @Override
                    public void onUploadFailed(UploadConf config, String failed) {
                        configs.add(config);
                        reUpload(photos, index + 1);
                    }
                });
    }



    private void doCompressAndUploadPhoto(final List<String> photos, final int index) {
        if (index >= photos.size()) {
            view.onPictureUploadFinished(configs);
            return;
        }
        Log.d(TAG, "doCompressAndUploadPhoto " + index);
        File handled = new File(photos.get(index));
        try {
            handled = Compressor.compress(handled);
        } catch (Exception e) {
            handled = new File(photos.get(index));
        }
        UploadMgr.getInstance().uploadImage(handled.getAbsolutePath(),
                UploadMgr.UPLOAD_TYPE_RECORD, InitManager.getInstance().getUserId(), new UploadMgr.UploadListener() {
                    @Override
                    public void onQueryToken() {
                    }

                    @Override
                    public void onStartUpload() {

                    }

                    @Override
                    public void onUploadProgress(int total) {

                    }

                    @Override
                    public void onUploadSuccess(UploadConf config) {
                        configs.add(config);
                        doCompressAndUploadPhoto(photos, index + 1);
                    }

                    @Override
                    public void onUploadFailed(UploadConf config, String failed) {
                        configs.add(config);
                        doCompressAndUploadPhoto(photos, index + 1);
                    }
                });
    }

}
